package it.fantacalcio.struts.action;

import java.util.List;

import it.fantacalcio.model.Classifica;
import it.fantacalcio.model.User;
import it.fantacalcio.spring.service.MyServiceFactory;
import it.fantacalcio.struts.form.LoginForm;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class LoginAction extends Action {
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		LoginForm loginform=(LoginForm)form;
		try{
			User user=new User();
			user=MyServiceFactory.getUserService().login(loginform.getUsername(),loginform.getPassword());
			if(user!=null){
				List<Classifica> listaClassifica = MyServiceFactory.getClassificaService().list();
				HttpSession session = request.getSession();
				session.setAttribute("userInSession",user);
				session.setAttribute("squadraInSession", MyServiceFactory.getSquadraService().getByPresidente(user));
				request.setAttribute("listaClassifica", listaClassifica.size() == 0 ? null : listaClassifica);
				return mapping.findForward("login");
			}
		}catch (Exception e) {
			e.printStackTrace();
			return mapping.findForward("error");
		}
		request.setAttribute("msg", "Non Autorizzato");
		return mapping.findForward("nonautorizzato");
	}
}
